package com.im.service.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjUtil;
import com.im.service.common.Result;
import com.im.service.common.ServiceException;
import com.im.service.domain.dto.ImChatDTO;
import com.im.service.domain.query.ChatHistoryQuery;
import com.im.service.domain.vo.ChatHistoryVO;
import com.im.service.domain.vo.ChatVO;
import com.im.service.job.SyncUserCache;
import com.im.service.service.ImChatService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 聊天列表 前端控制器
 * </p>
 *
 * @author 刘志强
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/imChat")
@CrossOrigin
@Slf4j
@Api(tags = "聊天界面会话界面接口")
public class ImChatController {

    @Autowired
    private ImChatService chatService;
    @Autowired
    private SyncUserCache syncUserCache;

    @GetMapping("/pageList")
    @ApiOperation(value = "我的聊天")
    public Result<List<ChatVO>> myChat() {
        return chatService.myChat();
    }

    @PostMapping("/historyByTargetId")
    @ApiOperation(value = "与指定用户或群组的聊天记录(时间倒叙分页,消息内容为ws消息内容)")
    public Result<ChatHistoryVO> historyByTargetId(@RequestBody ChatHistoryQuery query) {
        if (ObjUtil.isNotNull(query.getStartIndex()) && 0L > query.getStartIndex()) {
            query.setStartIndex(0L);
        }
        return chatService.historyByTargetId(query);
    }

    @PostMapping("/createChat")
    @ApiOperation(value = "创建会话")
    public Result createChat(@RequestBody ImChatDTO chatDTO) {
        chatDTO.setUserId(StpUtil.getLoginIdAsLong());
        if (ObjUtil.equal(chatDTO.getUserId(), chatDTO.getTargetUserId())) {
            throw new ServiceException("不可以和自己聊天");
        }
        return chatService.createChat(chatDTO);
    }

    @DeleteMapping("/removeChat")
    @ApiOperation(value = "移除会话")
    public Result removeChat(Long id) {
        chatService.removeChat(id);
        return Result.ok();
    }

    @PostMapping("/syncUserCache")
    @ApiOperation(value = "同步用户会话")
    public Result syncUserCache() {
        syncUserCache.syncUserCache();
        return Result.ok();
    }
}
